package com.huarun.module.sys.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import com.huarun.common.HeadAuthorization;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.MyException;
import com.huarun.common.util.PropertyUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.ResultCodeValue;
import com.huarun.common.util.SpringContextUtils;
import com.huarun.common.util.SpringUtils;
import com.huarun.common.util.StringUtils;
import com.huarun.module.sys.bean.Subject;
import com.huarun.module.sys.service.ISubjectServiceNew;
import com.huarun.module.sys.service.impl.SubjectServiceImplNew;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.util.LesseeInfoUtil;
import com.huarun.module.webapi.IChunSunServiceApi;
import com.huarun.module.webapi.facePlus.ChunSunServiceApiImpl;
import com.huarun.redis.RedisKeyPrefix;
import com.huarun.redis.RedisUtils;

@Component
@DependsOn("springContextUtils")
public class UserInfoUtil {
	private static RedisUtils redis = null;
	private static ISubjectServiceNew subjectService = (ISubjectServiceNew) SpringContextUtils
			.getBeanByClass(SubjectServiceImplNew.class);
	
	private static IChunSunServiceApi chunSunService = (IChunSunServiceApi) SpringContextUtils
			.getBeanByClass(ChunSunServiceApiImpl.class);

	public static String getRedisInfo(RedisKeyPrefix keyPrefix, String key) {
		if (redis == null) {
			redis = SpringUtils.getBean(RedisUtils.class);
		}
		if (null == key) {
			throw new MyException(ResultCodeValue.R_ERROR, "传入openId为空");
		}
		System.out.println("redis.get(keyPrefix, key)" + key);
		return redis.get(keyPrefix, key);

	}

	public static String setRedisInfo(RedisKeyPrefix keyPrefix, String key, String value) {

		if (redis == null) {
			redis = SpringUtils.getBean(RedisUtils.class);
		}
		if (null == key) {
			throw new MyException(ResultCodeValue.R_ERROR, "传入openId为空");
		}
		return redis.set(keyPrefix, key, value);
	}

	public static ResponseMessage<String> checkUserRole(HttpServletRequest req) throws UnsupportedEncodingException {
		String openId = req.getHeader("openId");
		String projectId = req.getHeader("projectId");
		String roleUpdate = req.getHeader("roleUpdate");
		System.out.println("roleUpdate======" + roleUpdate);
		String phone = null;
		int admin = 0;
		ResponseMessage<String> rMessage = new ResponseMessage<String>();
		HeadAuthorization headAuth = UserInfoUtil.getLoginHeadInfo(req);
		// 适配小程序，过滤未授权分支 redis by mengsg
		if("".equals(headAuth.getPhone())||headAuth.getPhone()==null) {
			rMessage.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			return rMessage;
		}
		// 通过Head中的openId，得到SessionKey 用于后续的解密
		String redisUserInfo = UserInfoUtil.getRedisInfo(RedisKeyPrefix.USER_INFO, openId);
		Map<String, Object> redisMap = StringUtils.stringConvertMap(redisUserInfo);
		if (redisMap.size() > 0) {
			phone = (String) redisMap.get("phone");
			System.out.println("redisMap.get(\"admin\")=====" + redisMap.get("admin"));
			if (null != redisMap.get("admin")) {
				admin = Integer.parseInt((String) redisMap.get("admin"));
			}
		}

		// 去数据库中查询已登录的用户数据，如果没有，再去运营平台的接口中查询用户数据，再没有的话，定义这个人为访客，
		Map<String, Object> map = new HashMap<>();
		map.put("openId", openId);
		map.put("wxPhone", phone);
		String info = LesseeInfoUtil.getTenantInfoByTelAndProId(req, phone);
		User rgUser = LesseeInfoUtil.formartLesseeinfo2(info, phone);
		User tenantUser = null;

		/***
		 * 4.获取face++或访客中的一般租户信息,如果项目ID为春笋，那么就去查春笋访客系统数据，如果不为春笋，则去查face++同步的 Subject表的数据
		 ***/
		// 针对系统,因为有可能出现运营平台随便加了一个公司，而访客系统里面不存在这个公司
		boolean isTrueManager = false;
		boolean isChunsun = PropertyUtil.getProperty("chunsun_project_id").equals(req.getHeader("projectId"));
		if (isChunsun) {
			// 访问春笋的接口
			Map<String,Object> chunSunMap=chunSunService.chunsunGetEmployee(phone);
			if(null!=chunSunMap && chunSunMap.size()>0) {
				String department=(String) chunSunMap.get("companyName");
				String floor = (String) chunSunMap.get("floor");
				String mainAdminInfo = LesseeInfoUtil.getTenantInfoByDeptNameAndProId(req,
						URLEncoder.encode(department, "UTF-8"));
				tenantUser = LesseeInfoUtil.formartLesseeinfo2(mainAdminInfo, null);
				if (null != tenantUser && tenantUser.getAdmin() == Constant.MAIN_ADMIN_ROLE) {
					tenantUser.setAccountNo((String) map.get("tel"));
					tenantUser.setDeptName(department);
					tenantUser.setUserName((String) map.get("empName"));
					tenantUser.setOpenId(openId);
					tenantUser.setWxPhone((String) map.get("tel"));
					tenantUser.setAdmin(Constant.LESSEE_ROLE);
					tenantUser.setFloor(floor);
					if(rgUser != null && !StringUtils.isEmpty(rgUser.getDeptName()) && rgUser.getDeptName().equals(department)){
						isTrueManager = true;
					}
				}
			}
		} else {
			/** 5.如果这个人是租户，那么去戎光中获取主管理信息 **/
			// 访问face++接口
			map.put("phone", phone);
			map.put("projectId", projectId);
			Subject subject = subjectService.getBeanByParams(map);
			if (null != subject) {
				String department = subject.getDepartment();
				String mainAdminInfo = LesseeInfoUtil.getTenantInfoByDeptNameAndProId(req,
						URLEncoder.encode(department, "UTF-8"));
				tenantUser = LesseeInfoUtil.formartLesseeinfo2(mainAdminInfo, null);
				if (null != tenantUser && tenantUser.getAdmin() == Constant.MAIN_ADMIN_ROLE) {
					tenantUser.setAccountNo(subject.getPhone());
					tenantUser.setDeptName(department);
					tenantUser.setUserName(subject.getRealName());
					tenantUser.setFaceId(subject.getFaceId() + "");
					tenantUser.setOpenId(headAuth.getOpenId());
					tenantUser.setWxPhone(subject.getPhone());
					tenantUser.setAdmin(Constant.LESSEE_ROLE);//普通用户
					if(rgUser != null && !StringUtils.isEmpty(rgUser.getDeptName()) && rgUser.getDeptName().equals(department)){
						isTrueManager = true;
					}
				}
			}
		}
		int currentAdmin=Constant.VISITOR_ROLE;
		if(null!=rgUser) {
			if(isTrueManager){
				currentAdmin = Constant.MAIN_ADMIN_ROLE;
			}else if(tenantUser != null){
				currentAdmin = Constant.LESSEE_ROLE;
			}
		}else {
			//如果访客数据不为空,则当前角色指定为普通用户
			if(null!=tenantUser) {
				currentAdmin=Constant.LESSEE_ROLE;
			}
		}

		if(0!=admin && currentAdmin!=admin  && (roleUpdate == null || roleUpdate.equals("false"))) {
			rMessage.setMessage("用户角色已改变，即将使用新角色");
			rMessage.setCode(ResultCodeValue.R_ROLE_IS_CHANGE);
			return rMessage;
		}

		rMessage.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
		return rMessage;

	}

	/**
	 * 从请求头里获取到openId 项目信息，以及用户电话等
	 * @param req
	 * @return
	 */
	public static HeadAuthorization getLoginHeadInfo(HttpServletRequest req) {
		HeadAuthorization headAuth = new HeadAuthorization();
		System.out.println("================"+req.getHeader("openId"));
		headAuth.setOpenId(req.getHeader("openId"));
		headAuth.setProjectId(req.getHeader("projectId"));
		headAuth.setRoleUpdate(req.getHeader("roleUpdate"));
		headAuth.setSessionKey(UserInfoUtil.getRedisInfo(RedisKeyPrefix.USER_TOKEN, req.getHeader("openId")));
		headAuth.setSessionKeyValue(UserInfoUtil.getRedisInfo(RedisKeyPrefix.USER_INFO, req.getHeader("openId")));
		if (null != headAuth.getSessionKeyValue()) {
			Map<String, Object> map = StringUtils.stringConvertMap(headAuth.getSessionKeyValue());
			if (null != map && map.size() > 0) {
				headAuth.setPhone((String) map.get("phone"));
			}
		}
		return headAuth;
	}

	/**
	 * 转换face++数据为数据库存储的格式，房间号和主租户ID 待后续set
	 * @param subject
	 * @return
	 */
	public static User tranfUser(HeadAuthorization headAuth, Subject subject) {
		User u = new User();
		u.setAccountNo(subject.getPhone());
		u.setDeptName(u.getDeptName());
		u.setUserName(subject.getRealName());
		u.setOpenId(headAuth.getOpenId());
		u.setWxPhone(subject.getPhone());
		return u;
	}

	//	public static void main(String[] args) {
	////		new UserInfoUtil();
	//		Map<String,Object> map=new HashMap<String,Object>();
	//		map.put("phone", "17392553112");
	//		map.put("projectId","a3697350-929a-f808-f97e-c6b9f499059b");
	//		Subject subject = testBeanDao.getSubjectByParams(map);
	//		System.out.println(subject.getDepartment());
	//		
	//	}

}
